<!-- 组件名: index -->
<!-- 创建日期: 2023/12/25 -->
<!-- 编写者: Adil -->

<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="接口名称" prop="interfaceName">
            <el-input
                v-model="queryParams.interfaceName"
                placeholder="请输入接口名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="URL" prop="url">
            <el-input
                v-model="queryParams.url"
                placeholder="请输入url"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="info"
                plain
                icon="el-icon-back"
                size="mini"
                @click="handleBack"
            >后退</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="el-icon-star-off"
                size="mini"
                @click="changeStar"
            >预览</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="接口名称" align="center" key="interfaceName" prop="interfaceName" v-if="columns[0].visible" :show-overflow-tooltip="true" />
          <el-table-column label="URL" align="center" key="url" prop="url" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="请求方式" align="center" key="method" prop="method" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="版本" align="center" key="version" prop="version" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="修改时间" align="center" key="createTimeStr" prop="createTimeStr" v-if="columns[4].visible" :show-overflow-tooltip="true">
            <template #default="scope">
              {{ formatTime(scope.row.createTimeStr) }}
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加与编辑对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="80%" width="600px" append-to-body>
      <template #title>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
      <div class="drawer_boder">
        <div class="ng-scope">
          基础信息
          <span class="C9999 f12">（带 * 的为必填项）</span>
        </div>
        <div>
          <el-form ref="form" class="table-bordered" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="12" class="Col_bor">
                <el-form-item label="接口昵称" prop="interfaceName">
                  <el-input v-model="form.interfaceName" placeholder="示例：获取用户列表接口" maxlength="100" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="模块名称" prop="moduleName">
                  <el-input v-model="form.moduleName" placeholder="请选择模块" />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="Url" prop="url">
                  <el-input v-model="form.url" placeholder="示例：http://localhost:3000/user" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="请求方式" prop="method">
                  <el-select v-model="form.method" placeholder="" style="width: 100%;">
                    <el-option
                        v-for="item in options_Way"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="版本号" prop="version">
                  <el-input v-model="form.version" placeholder="请输入版本号" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="返回类型">
                  <el-select v-model="form.contentType" placeholder="" style="width: 100%;">
                    <el-option
                        v-for="item in options_contentType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="接口说明" prop="remark">
                  <mk-md-editor  v-model="form.remark" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="ng-scope2">
          <a href="https://baike.baidu.com/item/http%E8%AF%B7%E6%B1%82%E5%A4%B4/6623287"  target="_blank">请求头</a>
          <el-tooltip class="item" effect="dark" content="「Cookie,Content-Type等，Content-Type会自动生成，如需自定义请删除系统自动生成后再添加」" placement="right">
            <el-button type="text">
              <svg-icon icon-class="wenhao" class="el-input__icon input-icon"></svg-icon>
            </el-button>
          </el-tooltip>

          <span style="float: right">
            <el-button type="text">导入头部</el-button>
            <el-button type="text" @click="addDomain">添加一行</el-button>
          </span>
        </div>
        <div>
          <el-table :data="StatusList" border class="inputDeep">
            <el-table-column label="名称" align="center" key="name" prop="name">
              <template #default="scope">
                <el-input v-model="scope.row.name"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="必填" align="center" key="necessary" prop="necessary">
              <template #default="scope">
                <el-select v-model="scope.row.necessary" placeholder="">
                  <el-option
                      v-for="item in options_necessary"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="类型" align="center" key="type" prop="type">
              <template #default="scope">
                <el-select v-model="scope.row.type" placeholder="">
                  <el-option
                      v-for="item in options_Type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="默认值" align="center" key="realName" prop="realName">
              <template #default="scope">
                <el-input v-model="scope.row.realName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" key="remark" prop="remark">
              <template #default="scope">
                <el-input v-model="scope.row.remark"></el-input>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="160"
                class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click.prevent="handleStatusDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div style="margin-top: 20px; border-left: 3px solid #5bc0de;" class="ng-scope2">
          <span>请求参数</span>
          <el-tooltip class="item" effect="dark" content="「支持普通表单参数、自定义参数（row、json、xml等格式）」" placement="right">
            <el-button type="text">
              <svg-icon icon-class="wenhao" class="el-input__icon input-icon"></svg-icon>
            </el-button>
          </el-tooltip>

          <span style="float: right">
            <el-button type="text">导入头部</el-button>
            <el-button type="text" @click="addReq">添加一行</el-button>
          </span>
        </div>

        <el-table :data="ReqList" border class="inputDeep">
          <el-table-column label="名称" align="center" key="name" prop="name">
            <template #default="scope">
              <el-input v-model="scope.row.name"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="必填" align="center" key="necessary" prop="necessary">
            <template #default="scope">
              <el-select v-model="scope.row.necessary" placeholder="">
                <el-option
                    v-for="item in options_necessary"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="位置" align="center" key="paramPosition" prop="paramPosition">
            <template #default="scope">
              <el-select v-model="scope.row.paramPosition" placeholder="">
                <el-option
                    v-for="item in options_ParamPosition"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center" key="type" prop="type">
            <template #default="scope">
              <el-select v-model="scope.row.type" placeholder="">
                <el-option
                    v-for="item in options_Type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="默认值" align="center" key="realName" prop="realName">
            <template #default="scope">
              <el-input v-model="scope.row.realName"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" key="remark" prop="remark">
            <template #default="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.prevent="handleReqDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 20px; border-left: 3px solid #f0ad4e;" class="ng-scope2">
          <span>返回参数</span>
          <el-tooltip class="item" effect="dark" content="「多级结构请使用'->'，如：参数1->参数1的子参数->....」" placement="right">
            <el-button type="text">
              <svg-icon icon-class="wenhao" class="el-input__icon input-icon"></svg-icon>
            </el-button>
          </el-tooltip>

          <span style="float: right">
            <el-button type="text">导入头部</el-button>
            <el-button type="text" @click="addRes">添加一行</el-button>
          </span>
        </div>

        <el-table :data="ResList" border class="inputDeep">
          <el-table-column label="名称" align="center" key="name" prop="name">
            <template #default="scope">
              <el-input v-model="scope.row.name"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="必填" align="center" key="necessary" prop="necessary">
            <template #default="scope">
              <el-select v-model="scope.row.necessary" placeholder="">
                <el-option
                    v-for="item in options_necessary"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center" key="type" prop="type">
            <template #default="scope">
              <el-select v-model="scope.row.type" placeholder="">
                <el-option
                    v-for="item in options_Type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" key="remark" prop="remark">
            <template #default="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.prevent="handleResDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import store from "@/store";
import {
  GetConnectorAdd,
  GetConnectorDelete,
  GetConnectorList,
  GetConnectorListId,
  GetConnectorUpdate
} from "@/api/connector";
import {GetProjectID} from "@/api/project";
import {formatTime} from "../../../../utils/adil";
import MkMdEditor from "@/components/md-editor/index.vue";

export default {
  name: "index",
  components: {MkMdEditor, Pagination, RightToolbar},
  data() {
    return {
      // 查询参数
      queryParams: {
        id: this.$route.params.id,
        pageNum: 1,
        pageSize: 10,
        interfaceName: '',
        url: ''
      },
      // 显示搜索条件
      showSearch: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 列信息
      columns: [
        { key: 0, label: `接口名称`, visible: true },
        { key: 1, label: `URL`, visible: true },
        { key: 2, label: `请求方式`, visible: true },
        { key: 3, label: `版本`, visible: true },
        { key: 4, label: `修改时间`, visible: true }
      ],
      // 遮罩层
      loading: false,
      // 用户表格数据
      userList: null,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 表单参数
      form: {
        interfaceName: '',
        moduleName: '',
        url: '',
        method: '',
        version: '',
        contentType: '',
        remark: '',
        projectId: '',
        projectName: '',
        userName: store.state.user.name,
        headers: null,
        req: null,
        res: null
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入项目名称", trigger: 'blur' }
        ],
        remark: [
          { required: true, message: "请输入项目简介", trigger: 'blur' }
        ],
        cover: [
          { required: true, message: "请上传项目封面", trigger: 'blur' }
        ]
      },
      // 状态码头部参数
      StatusList: [
        {
          name: '',
          remark: '',
          type: '',
          necessary: '',
          realName: ''
        }
      ],
      // 状态码请求参数对象
      ReqList: [
        {
          name: '',
          remark: '',
          type: '',
          necessary: '',
          realName: '',
          paramPosition: ''
        }
      ],
      // 状态码返回参数对象
      ResList: [
        {
          name: '',
          remark: '',
          type: '',
          necessary: ''
        }
      ],

      options_necessary: [
        {
          value: '0',
          label: '否'
        },
        {
          value: '1',
          label: '是'
        }
      ],

      options_contentType: [
        {
          value: 'application/json',
          label: 'application/json'
        },
        {
          value: 'text/html',
          label: 'text/html'
        },
        {
          value: 'x-application',
          label: 'x-application'
        },
        {
          value: 'application/xml',
          label: 'application/xml'
        }
      ],

      options_Way: [
        {
          value: 'POST',
          label: 'POST'
        },
        {
          value: 'GET',
          label: 'GET'
        },
        {
          value: 'PUT',
          label: 'PUT'
        },
        {
          value: 'HEAD',
          label: 'HEAD'
        },
        {
          value: 'DELETE',
          label: 'DELETE'
        },
        {
          value: 'OPTIONS',
          label: 'OPTIONS'
        },
        {
          value: 'TRACE',
          label: 'TRACE'
        },
        {
          value: 'PATCH',
          label: 'PATCH'
        }
      ],

      options_Type: [
        {
          value: 'string',
          label: 'string'
        },
        {
          value: 'int',
          label: 'int'
        },
        {
          value: 'float',
          label: 'float'
        },
        {
          value: 'long',
          label: 'long'
        },
        {
          value: 'byte',
          label: 'byte'
        },
        {
          value: 'double',
          label: 'double'
        },
        {
          value: 'number',
          label: 'number'
        },
        {
          value: 'boolean',
          label: 'boolean'
        },
        {
          value: 'object',
          label: 'object'
        },
        {
          value: 'array',
          label: 'array'
        },
        {
          value: 'array[int]',
          label: 'array[int]'
        },
        {
          value: 'file',
          label: 'file'
        }
      ],

      options_ParamPosition: [
        {
          value: '普通参数',
          label: '普通参数'
        },
        {
          value: 'URL路径',
          label: 'URL路径'
        }
      ]
    };
  },
  mounted() {
  },
  created() {
    this.getList()
  },
  methods: {
    formatTime,
    getList() {
      this.loading = false
      GetConnectorList(this.queryParams).then(res => {
        this.userList = res.result;
        this.total = res.total;
        this.loading = false
      })
    },

    reset() {
      this.form = {
        interfaceName: '',
        moduleName: '',
        url: '',
        method: '',
        version: '',
        contentType: '',
        remark: '',
        projectId: '',
        projectName: '',
        userName: store.state.user.name,
        headers: null,
        req: null,
        res: null
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.errorMsg = undefined;
      this.queryParams.errorCode = undefined
      this.handleQuery();
    },
    handleBack() {
      this.$router.back()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item._id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新建接口'
      GetProjectID(this.$route.params.id).then(res => {
        this.form.projectName = res.result[0].name
        this.form.projectId = res.result[0]._id
      })
    },

    /** 预览按钮操作 */
    changeStar() {
      this.$router.push("/preview/" + this.$route.params.id)
    },

    /** 前端添加一条headers请求头 */
    addDomain() {
      this.StatusList.push({})
    },

    /** 前端假删除 */
    handleStatusDelete(item) {
      const index = this.StatusList.indexOf(item);
      if (index !== -1) {
        this.StatusList.splice(index, 1)
      }
    },

    /**  前端添加一条请求参数 */
    addReq() {
      this.ReqList.push({})
    },
    /** 前端删除一条请求参数数据 */
    handleReqDelete(item) {
      const index = this.ReqList.indexOf(item);
      if (index !== -1) {
        this.ReqList.splice(index, 1)
      }
    },

    /** 前端添加一条返回参数 */
    addRes() {
      this.ResList.push({})
    },
    /** 前端删除一条返回参数数据 */
    handleResDelete(item) {
      const index = this.ResList.indexOf(item);
      if (index !== -1) {
        this.ResList.splice(index, 1)
      }
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const userId = row._id || this.ids;
      GetConnectorListId(userId).then(res => {
        this.form = res.result[0]
        this.StatusList = res.result[0].headers
        this.ReqList = res.result[0].req
        this.ResList = res.result[0].res
        this.open = true
        this.title = '更新接口'
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row._id || this.ids
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return GetConnectorDelete(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },

    /** 提交按钮 */
    submitForm: function () {
      this.form.headers = this.StatusList
      this.form.req = this.ReqList
      this.form.res = this.ResList
      this.$refs["form"].validate(async valid => {
        if (valid) {
          console.log(this.form)
          if (this.title != '新建接口') {
            await GetConnectorUpdate(this.form._id, this.form)
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          } else {
            GetConnectorAdd(this.form).then(res => {
              console.log(res)
              this.$modal.msgSuccess("成功");
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.drawer_boder {
  box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.2);
  background: #FFF;
  width: 100%;

  .ng-scope {
    height: 40px;
    border-left: 3px solid #4e61d4;
    font-size: 16px;
    padding-left: 20px;
    line-height: 40px;

    .f12 {
      font-size: 12px;
    }

    .C9999 {
      color: #999999;
    }
  }

  .table-bordered {
    padding: 10px;
    border: 1px solid #ddd;
  }

  .ng-scope2 {
    border-left: 3px solid #ff4530;
    min-height: 40px;
    font-size: 16px;
    padding-left: 20px;
    line-height: 40px;

    a {
      color: #1c84c6;
    }

    .el-input__icon {
      color: #ff4530!important;
    }

    .el-input__icon {
      margin-top: -3px!important;
      margin-left: 10px;
      color: #b71e1e;
    }
  }
}

/* 利用穿透，设置input边框隐藏 */
.inputDeep ::v-deep.el-input__inner {
  border: 0 !important;
  background: none;

  ::v-deep.el-input__inner :hover {
    background: none;
  }
}
/* 如果你的 el-input type 设置成textarea ，就要用这个了 */
.inputDeep ::v-deep.el-textarea__inner {
  border: 0 !important;
  resize: none;/* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
}

::v-deep .el-input__suffix {
  display: none;
}
::v-deep .el-select .el-input.is-disabled .el-input__inner ::placeholder{
  opacity:0
}

</style>
